package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class AutoTestUtils {
    public static WebDriver driver;

    public static WebDriver getDriver() {
        return driver;
    }

    /**
     * 创建驱动对象
     * @return driver
     */
    public static WebDriver createDriver(){
        //驱动对象已经创建好了/没有创建
        if(driver == null){
            //启动浏览器
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            //允许访问所有的连接
            options.addArguments("--remote-allow-origins=*");//避免访问403
            //设置浏览器加载策略
            options.setPageLoadStrategy(PageLoadStrategy.EAGER);
            //设置⽆头模式
            //options.addArguments("-headless");
            driver = new EdgeDriver(options);
            //创建隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
    public AutoTestUtils(String url){
        //调用driver对象
        driver = createDriver();
        //访问url
        driver.get(url);
    }


    /**
     * 获取屏幕截图，把所有的⽤例执⾏的结果保存下来（可以传类名和方法名）
     * @param className
     * @param methodName
     * @throws IOException
     */
    public void getScreenShot(String className, String methodName) throws IOException {
        // 屏幕截图
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        //文件存放路径：./src/test/image/2025-01-15/tests.ListPageTest-listPageRight-17425724.png
        String filename = "./src/test/image/" + dirTime + "/" + className + "-" + methodName + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        // srcFile放到指定位置
        FileUtils.copyFile(srcFile, new File(filename));
    }
}